<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import CreateQuestionPanel from '@/components/bank/create/CreateQuestionPanel.vue'
import QuestionGroupSettings from '@/components/bank/shared/QuestionGroupSettings.vue'
import QuestionList from '@/components/bank/shared/QuestionList.vue'
import BigButton from '@/components/common/BigButton.vue'
import FileUploader from '@/components/common/FileUploader.vue'
import message from '@/components/common/message'
import TextArea from '@/components/common/TextArea.vue'
import TextInput from '@/components/common/TextInput.vue'
import { KeyBoard, Upload } from '@/components/icons'
import { useQuestionGroup } from '@/hooks/bank/useQuestionGroup'
import { scanImageText } from '@/request/teacher/bank'

defineOptions({
  name: 'ReadingPage',
})

const router = useRouter()

// 使用共享的题目管理逻辑
const {
  questionList,
  editingQuestion,
  isCreateQuestionPopupVisible,
  questionGroupSettings,
  canSave,
  handleOpenCreateQuestion,
  handleOpenEditQuestion,
  handleCreateQuestion,
  handleCloseCreateQuestionPopup,
  removeQuestion,
  moveQuestionUp,
  moveQuestionDown,
  getEditingIndex,
  saveQuestionGroup,
  articleAuthor,
  articleContent,
  articleTitle,
} = useQuestionGroup()

// 文章输入相关状态
const isUploadFile = ref(true)
const isUploading = ref(false)
const textFromAI = ref(false)

// 文件上传处理
async function handleFileUpload(files: File[]) {
  if (!files.length)
    return

  const file = files[0]
  isUploading.value = true

  try {
    const result = await scanImageText(file)
    articleContent.value = result.entry.text
    textFromAI.value = true
    isUploadFile.value = false
  }
  catch (error) {
    handleUploadError(error instanceof Error ? error.message : '文件上传失败')
  }
  finally {
    isUploading.value = false
  }
}

function handleUploadError(_message: string) {
  console.error('上传错误:', _message)
  message.error(_message)
}

// 保存题组
async function handleSaveQuestionGroup() {
  if (!articleTitle.value) {
    message.error('请填写文章题目')
    return
  }
  if (!articleAuthor.value) {
    message.error('请填写文章作者')
    return
  }
  if (!articleContent.value) {
    message.error('请填写文章内容')
    return
  }
  await saveQuestionGroup({
    title: articleTitle.value,
    author: articleAuthor.value,
    content: articleContent.value,
  }).then(() => {
    router.push('/bank')
  })
}

// AI生题功能（待实现）
function handleAIGenerate() {
  // TODO: 实现AI生题功能
  message.info('AI生题功能正在开发中')
}
</script>

<template>
  <div class="card-area">
    <div class="card-header">
      <div class="card-title">
        阅读文本
      </div>
      <div class="card-opr-container">
        <button
          class="input-type-button"
          :class="{ 'active-button': isUploadFile }"
          @click="isUploadFile = true"
        >
          <Upload color="white" />
          上传文件
        </button>
        <button
          class="input-type-button"
          :class="{ 'active-button': !isUploadFile }"
          @click="isUploadFile = false, textFromAI = false"
        >
          <KeyBoard />
          输入文本
        </button>
      </div>
    </div>

    <FileUploader
      v-show="isUploadFile"
      :accepted-types="['.jpg', '.jpeg', '.png', '.bmp', '.webp']"
      :disabled="isUploading"
      @upload="handleFileUpload"
      @error="handleUploadError"
    />

    <div v-show="!isUploadFile" class="text-input-area">
      <TextInput
        v-model="articleTitle"
        class="title-input"
        label="文章题目:"
        placeholder="请输入文章题目"
      />
      <TextInput
        v-model="articleAuthor"
        class="title-input"
        label="文章作者:"
        placeholder="请输入文章作者"
      />
      <TextArea
        v-model="articleContent"
        placeholder="请在此粘贴或输入文章内容......"
        :min-height="200"
        :max-height="200"
      />
      <div v-if="articleContent && textFromAI" class="beeAI">
        <div>
          <img src="/beeAI.png" alt="beeAI">
        </div>
        <div>识别结果由蜜蜂AI提供</div>
      </div>
    </div>
  </div>
  <QuestionList
    :questions="questionList"
    @create-question="handleOpenCreateQuestion"
    @edit-question="handleOpenEditQuestion"
    @remove-question="removeQuestion"
    @move-question-up="moveQuestionUp"
    @move-question-down="moveQuestionDown"
    @ai-generate="handleAIGenerate"
  />
  <QuestionGroupSettings v-model="questionGroupSettings" />

  <BigButton
    class="save-btn"
    text="保存题组"
    :disabled="!canSave"
    @click="handleSaveQuestionGroup"
  />

  <CreateQuestionPanel
    v-if="isCreateQuestionPopupVisible"
    :init-question="editingQuestion"
    :visible="isCreateQuestionPopupVisible"
    :editing-index="getEditingIndex()"
    @close="handleCloseCreateQuestionPopup"
    @confirm="handleCreateQuestion"
  />
</template>

<style scoped>
.save-btn {
  margin-top: 2rem;
}

.card-area {
  padding: 12px 19px 20px 19px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 18px;

  .card-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;

    .card-title {
      font-size: 18px;
      font-weight: bold;
      color: #333333;
    }

    .card-opr-container {
      display: flex;
      gap: 8px;

      button {
        padding: 6px 19px;
        border-radius: 5px;
        display: flex;
        align-items: center;
        gap: 4px;
        letter-spacing: 0.01em;
        background: linear-gradient(93.74deg, #7a91fe -11.82%, #284af9 116.56%);
        color: white;
        border: none;
        cursor: pointer;

        svg {
          transform: scale(1.2);
          width: 1rem;
          stroke: white;
        }
      }

      .input-type-button:not(.active-button) {
        color: black;
        background: transparent;

        svg {
          stroke: black;
        }
      }
    }
  }
}

.text-input-area {
  display: flex;
  flex-direction: column;
  gap: 12px;

  .title-input {
    width: 40%;
  }
}

.beeAI {
  display: flex;
  flex-direction: column;
  align-items: center;
  letter-spacing: 0.15em;
  font-size: 12px;
  color: #898989;
}
</style>
